package com.yxq.mdt.app.modules.personal.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.orhanobut.hawk.Hawk;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.application.App;
import com.yxq.mdt.app.application.UmengShareHelper;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.Constant;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.dialog.CostumerDialog;
import com.yxq.mdt.app.glide.GlideCacheUtil;
import com.yxq.mdt.app.modules.login.bean.UserBean;
import com.yxq.mdt.app.modules.login.model.LoginModel;
import com.yxq.mdt.app.modules.login.ui.BindPhoneActivity;
import com.yxq.mdt.app.modules.login.ui.LoginActivity;
import com.yxq.mdt.app.modules.login.ui.UpdatePhoneActivity;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.StringUtils;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 设置界面
 */
public class MainPersonalSettingsAc extends BaseActivity {
    @BindView(R.id.setting_btn_exit)
    Button settingBtnExit;
    @BindView(R.id.setting_tv_bind_phone)
    TextView settingTvBindPhone;
    @BindView(R.id.setting_tv_privacy)
    TextView settingTvPrivacy;
    @BindView(R.id.setting_tv_suggest)
    TextView settingTvSuggest;
    @BindView(R.id.setting_tv_clear_cache)
    TextView settingTvClearCache;
    @BindView(R.id.setting_tv_cache_size)
    TextView settingTvCacheSize;
    @BindView(R.id.setting_tv_bind_phone_show)
    TextView settingTvBindPhoneShow;
    @BindView(R.id.setting_tv_bind_wechat_show)
    TextView settingTvBindWechatShow;
    @BindView(R.id.setting_tv_check_version)
    TextView settingTvCheckVersion;
    @BindView(R.id.setting_tv_version)
    TextView settingTvVersion;
    @BindView(R.id.setting_tv_bind_wechat_status)
    TextView settingTvBindWechatStatus;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main_personal_settings;
    }

    @Override
    public void initView() {
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        settingTvCacheSize.setText(GlideCacheUtil.getInstance().getCacheSize(this));
        settingTvVersion.setText(AppUtils.getAppVersionName());
    }

    @OnClick(R.id.setting_btn_exit)
    public void onViewClicked() {
        exit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initUser();
    }

    private void initUser() {
        UserBean userBean = Constant.getLoginUser();
        if (userBean != null) {
            if (!StringUtils.isEmpty(userBean.getBinding()) && !"null".equals(userBean.getBinding())) {
                settingTvBindPhoneShow.setText(userBean.getBinding().substring(0, 3) + "*****" + userBean.getBinding().substring(userBean.getBinding().length() - 3, userBean.getBinding().length()));
            }
            if (!StringUtils.isEmpty(userBean.getWechat_union_id()) && !"null".equals(userBean.getWechat_union_id())) {
                settingTvBindWechatShow.setText(userBean.getWechat_nickname());
                settingTvBindWechatStatus.setText("已绑定");
            } else {
                settingTvBindWechatShow.setText("");
                settingTvBindWechatStatus.setText("去绑定");
            }
        }
    }

    /**
     * 退出确认弹出框
     */
    private void exit() {
        CostumerDialog dialog = new CostumerDialog.Builder(this, R.style.custom_dialog_no_match)
                .setContentView(R.layout.dialog_clear_cache_layout)
                .setCancelable(true)
                .create();

        TextView title = dialog.findViewById(R.id.tv_title);

        title.setText("");

        TextView content = dialog.findViewById(R.id.tv_content);
        content.setText("确定退出登录？");

        //继续
        TextView sure = dialog.findViewById(R.id.tv_sure);
        sure.setText("确定");
        sure.setOnClickListener(v -> {
            dialog.dismiss();
            loginOut();
        });

        //取消
        TextView cancel = dialog.findViewById(R.id.tv_cancel);
        cancel.setText("取消");
        cancel.setOnClickListener(v -> {
            dialog.dismiss();
        });

        dialog.show();
    }

    /**
     * 退出登录
     */
    private void loginOut() {
        showLoadingDialog();
        EMClient.getInstance().logout(true, new EMCallBack() {
            @Override
            public void onSuccess() {
                hideLoadingDialog();
                Hawk.delete(SPKey.SP_KEY_USER_MY_INFO);
                Hawk.delete(SPKey.SP_KEY_USER_INFO);
                App.getInstance().exit();
                Intent intent = new Intent(mActivity, LoginActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onError(int i, String s) {
                hideLoadingDialog();
                Hawk.delete(SPKey.SP_KEY_USER_MY_INFO);
                Hawk.delete(SPKey.SP_KEY_USER_INFO);
                App.getInstance().exit();
                Intent intent = new Intent(mActivity, LoginActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onProgress(int i, String s) {
                ToastUtils.showShort(s);
            }
        });
    }

    @OnClick({R.id.setting_tv_bind_phone, R.id.setting_tv_privacy, R.id.setting_tv_suggest, R.id.setting_tv_clear_cache, R.id.setting_tv_bind_wechat, R.id.setting_tv_check_version})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.setting_tv_bind_phone://绑定手机
                bindPhone();
                break;
            case R.id.setting_tv_privacy://隐私设置
                Intent intent = new Intent(mActivity, PrivacySettingActivity.class);
                startActivity(intent);
                break;
            case R.id.setting_tv_suggest://意见反馈
                intent = new Intent(mActivity, SuggestActivity.class);
                startActivity(intent);
                break;
            case R.id.setting_tv_clear_cache://清除缓存
                clearCache();
                break;
            case R.id.setting_tv_bind_wechat://绑定微信
                bindWeChat();
                break;
            case R.id.setting_tv_check_version://检查新版本
                loadUpgradeInfo();
                break;
        }
    }

    /**
     * 检查APP更新
     */
    private void loadUpgradeInfo() {
        Beta.checkUpgrade(true, false);
//        try {
//            /***** 获取升级信息 *****/
//            UpgradeInfo upgradeInfo = Beta.getUpgradeInfo();
//
//            if (upgradeInfo == null) {
//                ToastUtils.showLong("当前是最新版本");
//            } else {
//                Beta.checkUpgrade();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 绑定微信
     */
    private void bindWeChat() {
        if (settingTvBindWechatStatus.getText().toString().equals("去绑定")) {
            UmengShareHelper.loginWX(mActivity, new UmengShareHelper.ShareSDKCallback<Map<String, String>>() {
                @Override
                public void onComplete(String name, Map<String, String> stringStringMap) {
                    showLoadingDialog(false);
                    LoginModel.bindWechat(stringStringMap.get("uid"), stringStringMap.get("name"), stringStringMap.get("iconurl"), new ApiModel.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String s) {
                            hideLoadingDialog();
                            ToastUtils.showShort("绑定成功");
                            UserBean userBean = Constant.getLoginUser();
                            userBean.setWechat_union_id(stringStringMap.get("uid"));
                            Hawk.delete(SPKey.SP_KEY_USER_INFO);
                            Hawk.put(SPKey.SP_KEY_USER_INFO, userBean);
                            settingTvBindWechatShow.setText(stringStringMap.get("screen_name"));
                            settingTvBindWechatStatus.setText("已绑定");
                        }

                        @Override
                        public void onError(String errMsg) {
                            hideLoadingDialog();
                            ToastUtils.showShort(errMsg);
                        }
                    });
                }

                @Override
                public void onError(String errMsg) {
                    ToastUtils.showShort(errMsg);
                }
            });
        } else {
            ToastUtils.showShort("不支持解绑");
        }
    }

    /**
     * 绑定手机号
     */
    private void bindPhone() {

        UserBean userBean = Constant.getLoginUser();
        if (userBean != null) {
            if (!StringUtils.isEmpty(userBean.getBinding()) && !"null".equals(userBean.getBinding())) {

                CostumerDialog dialog = new CostumerDialog.Builder(this, R.style.custom_dialog_no_match)
                        .setContentView(R.layout.dialog_clear_cache_layout)
                        .setCancelable(true)
                        .create();

                TextView title = dialog.findViewById(R.id.tv_title);

                title.setText("");

                TextView content = dialog.findViewById(R.id.tv_content);
                content.setText("确定修改手机号吗？");

                //继续
                TextView sure = dialog.findViewById(R.id.tv_sure);
                sure.setText("确定");
                sure.setOnClickListener(v -> {
                    dialog.dismiss();
                    Intent intent = new Intent(mActivity, UpdatePhoneActivity.class);
                    intent.putExtra("data", JSON.toJSONString(userBean));
                    intent.putExtra("finish", true);
                    startActivity(intent);
                });

                //取消
                TextView cancel = dialog.findViewById(R.id.tv_cancel);
                cancel.setText("取消");
                cancel.setOnClickListener(v -> {
                    dialog.dismiss();
                });
                dialog.show();
                return;
            }
        }
        Intent intent = new Intent(mActivity, BindPhoneActivity.class);
        intent.putExtra("data", JSON.toJSONString(userBean));
        intent.putExtra("finish", true);
        startActivity(intent);

    }

    /**
     * 清除缓存
     */
    private void clearCache() {
        CostumerDialog dialog = new CostumerDialog.Builder(this, R.style.custom_dialog_no_match)
                .setContentView(R.layout.dialog_clear_cache_layout)
                .setCancelable(true)
                .create();

        TextView title = dialog.findViewById(R.id.tv_title);

        title.setText("");

        TextView content = dialog.findViewById(R.id.tv_content);
        content.setText("确定清除缓存？");

        //继续
        TextView sure = dialog.findViewById(R.id.tv_sure);
        sure.setText("确定");
        sure.setOnClickListener(v -> {
            dialog.dismiss();
            clear();
        });

        //取消
        TextView cancel = dialog.findViewById(R.id.tv_cancel);
        cancel.setText("取消");
        cancel.setOnClickListener(v -> {
            dialog.dismiss();
        });

        dialog.show();
    }

    private void clear() {
        GlideCacheUtil.getInstance().clearImageAllCache(this);
        settingTvCacheSize.setText("0KB");
    }

}
